package com.vt.admin.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.vt.admin.api.dto.PositionTree;
import com.vt.admin.api.dto.user.redis.UserPosition;
import com.vt.admin.api.entity.SysPosition;
import com.vt.admin.api.vo.TreeUtil;
import com.vt.admin.mapper.SysPositionMapper;
import com.vt.common.core.constant.CommonConstant;
import com.vt.common.core.util.R;
import com.vt.common.security.util.OrganizationUtil;
import com.vt.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Auther: PanZha
 * @Date: 2018/11/1 17:58
 */
@Service
@AllArgsConstructor
public class SysPositionService implements CommandLineRunner {

    SysPositionMapper mapper;
    StringRedisTemplate redisTemplate;
    OrganizationUtil organizationUtil;

    @Async
    public void writeRedis() {
        List<UserPosition> list = mapper.selectUserPosition();
        redisTemplate.opsForValue().set(CommonConstant.REDIS_POSITION_PREFIX, JSONUtil.toJsonStr(list));
    }

    @Override
    public void run(String... args) {
        writeRedis();
    }

    public R<PositionTree> tree(String managerId) {
        /*if(StrUtil.isEmpty(managerId)){
            managerId = SecurityUtils.getUser().getCompanyId();
        }
        managerId = organizationUtil.searchOrgMgCompany(managerId);
        List<PositionTree> list = mapper.list(managerId);
        return new R(buildPositionTree(list));*/
        return null;
    }

    private List<PositionTree> buildPositionTree(List<PositionTree> list) {
        return TreeUtil.buildByRecursiveParent(list, "0");
    }

    public R<SysPosition> findOne(String id) {
        return new R(mapper.selectById(id));
    }

    public R<Boolean> save(SysPosition t) {
        String uId = SecurityUtils.getUser().getId();
        Date d = new Date();

        t.setUpdater(uId)
                .setUpdateTime(d);

        if (StrUtil.isEmpty(t.getId())) {
            t.setCreater(uId)
                    .setCreateTime(d)
                    .setEditable(1);
        }
        return new R(t.insertOrUpdate());
    }
}
